<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2015-8-25
 * Time: 10:13
 */
namespace common\components\services\message;

use common\components\helpers\EventData;
use common\models\datas\MessageLog;

class MailMessage extends Message
{
    public function send($id){
        $item=MessageLog::findOne([$id]);
        if ($item !=null && $item->receiver_arr!=null) {
            $receiver= unserialize($item->receiver_arr);
            $r_mail=[];
            $send_group_array=(new EventData())->getSendGroupArrayByKey($item->send_group);
            if($send_group_array!=null && $send_group_array['model']!=null){
                $model_class=$send_group_array['model'];
                $r_mail=$model_class::find()->where(['id'=>$receiver])->asArray()->all();
            }
            $fail_arr_mail=[];
            if(count($r_mail)>0){
                foreach($r_mail as $k=>$v){
                    if(!empty($v['email'])){
                        $status=\Yii::$app->mailer->compose()
                            ->setFrom('from@domain.com')
                            ->setTo($v['email'])
                            ->setSubject($item->content_mail)
                            ->send();
                        if(!$status){
                            $fail_arr_mail=$v['id'];
                        }
                    }else{
                        $fail_arr_mail=$v['id'];
                    }
                }
            }
            if(count($fail_arr_mail)>0){
                $fail_arr_mail=serialize($fail_arr_mail);
                $item->fail_arr_mail=$fail_arr_mail;
                $item->save(false);
                return false;
            }else{
                $log_status=unserialize($item->status);
                $log_status['email']=1;
                $item->status = serialize($log_status);
                $item->save(false);
                return true;
            }
        }
        return false;
    }
}